using UnityEngine;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
public class DataManager : MonoBehaviour
{
    public static DataManager Instance;
    private string savePath;
    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            //在场景切换时不销毁该对象
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
        //获取存档文件路径
        savePath = Path.Combine(Application.persistentDataPath, "saveData.json");
        Debug.Log(savePath);
    }

    private void Start()
    {
        if (!File.Exists(savePath)) Save(Resources.LoadAll<LevelList>("Data").ToList());
    }

    public void Save(List<LevelList> data)
    {
        string jsonData = JsonConvert.SerializeObject(data);
        File.WriteAllText(savePath, jsonData);
        Debug.Log("Save ok!");
    }
    public List<LevelList> Load()
    {
        //首先对路径做一个安全性检查
        if (File.Exists(savePath))
        {
            string jsonData = File.ReadAllText(savePath);
            var data = JsonConvert.DeserializeObject<List<LevelList>>(jsonData);
            //将JSON数据反序列化为游戏数据对象
            return data;
        }
        else
        {
            Debug.Log("Load null!");
            return null;
        }
    }
}